package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.db.WordMeaningDao;
import com.ezjie.ielts.model.CadicatesBean;
import com.ezjie.ielts.model.Eword;
import com.ezjie.ielts.model.EwordMeaning;
import com.ezjie.ielts.model.FilterWordData;
import com.ezjie.ielts.model.FilterWordResponse;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DateUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.SpeechTTSUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.ezjie.ielts.view.AutofitTextView;
import com.ezjie.ielts.view.FilterTimeRoundProgressBar;
import com.ezjie.ielts.widget.TitleTextView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

/**
 * 单词筛选
 * 
 * @author renyangyang
 *
 */
@ContentView(R.layout.layout_word_filter)
public class WordFilterActivity extends BaseFragmentActivity {
	private static final String TAG = WordFilterActivity.class.getSimpleName();
	// private static final int OUT_MSG = 1111;//外圆计时 消息
	private static final int IN_MSG = 2222;// 内圆计时 消息
	private static final int FLAG_INIT = 0;// 初始状态
	private static final int FLAG_KNOW = 1;// 认识
	private static final int FLAG_UNKNOW = 2;// 不认识
	private static final int FLAG_NOT_EXIST = 3;// 筛选的单词不存在

	private Context mContext;

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	@ViewInject(R.id.btn_unknown)
	private Button btn_unknown;// 不认识
	@ViewInject(R.id.btn_known)
	private Button btn_known;// 认识
	@ViewInject(R.id.iv_know)
	private ImageView iv_know;// 认识圆点
	@ViewInject(R.id.iv_unknow)
	private ImageView iv_unknow;// 不认识圆点
	@ViewInject(R.id.tv_word)
	private AutofitTextView tv_word;// 单词
	@ViewInject(R.id.tv_phonetic)
	private TextView tv_phonetic;// 单词的音标
	@ViewInject(R.id.ll_phonetic)
	private View ll_phonetic;
	@ViewInject(R.id.tv_knownNum)
	private TextView tv_knownNum;// 认识的数量
	@ViewInject(R.id.tv_unknownNum)
	private TextView tv_unknownNum;// 不认识的数量
	@ViewInject(R.id.rpb_timeProgress)
	private FilterTimeRoundProgressBar rpb_timeProgress;// 时间进度 外圆是一分钟，内圆是5s
	@ViewInject(R.id.iv_speak)
	private ImageView iv_speak;// 单词读

	private List<CadicatesBean> list;
	private List<Integer> knownList;
	private List<Integer> unknownList;
	private int currentPosition;// 当前位置
	private FilterWordData filterWordData;

	private int outTime = 0;// 外循环计时
	private int inTime = 0;// 内循环计时
	private boolean isPause;// 是否暂停了。
	// private boolean isTimeOut;//时间已经够1分钟了，但是 不认识单词未到十个
	private boolean isError;// 出现异常，筛词停止了
	private boolean isLoading;// 正在加载的时候，已经筛到最后一个了，那么就要显示 进度条
	private WordDao wordDao;
	private WordMeaningDao wordMeaningDao;
	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		ViewUtils.inject(this);

		mContext = this;
		YsApplication myApplication = (YsApplication) getApplication();
		filterWordData = myApplication.getFilterWordData();
		list = new ArrayList<CadicatesBean>();
		knownList = new ArrayList<Integer>();
		unknownList = new ArrayList<Integer>();
		wordDao = new WordDao(this);
		wordMeaningDao = new WordMeaningDao(this);
		mWordTask = new WordTask(this);

		SpeechTTSUtil.getInstance(this).init();

		init();
	}

	private void init() {
		iv_topbar_back.setOnClickListener(this);
		tv_topbar_title.setText(R.string.word_filter_title);

		btn_unknown.setOnClickListener(this);
		btn_known.setOnClickListener(this);
		iv_speak.setOnClickListener(this);
		rpb_timeProgress.setOutMax(60);// 60s
		rpb_timeProgress.setInMax(5000);// 5000ms

		if (filterWordData != null) {
			list = filterWordData.getCandidates();
		}
		initWord(FLAG_INIT);

		// 开始计时了
		startRecordTime();
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORD_FILTER);
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORD_FILTER);
	}

	private void startRecordTime() {
		Message inMessage = handler.obtainMessage();
		inMessage.what = IN_MSG;
		handler.sendMessageDelayed(inMessage, 100);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			if (msg.what == IN_MSG) {
				boolean isOver = false;
				if (!isPause) {
					inTime += 100;
					if (inTime >= 5000) {
						// 5s计时到了，开始下一个单词筛选
						rpb_timeProgress.setInProgress(5000);
						inTime = 0;
						if (currentPosition >= list.size() - 1) {
							// 要判断是否到最后一个单词了 请求新的单词序列
							handler.removeMessages(IN_MSG);
							unknown(false);
							return;
						}
						isOver = unknown(false);

					} else {
						// LogUtils.d("内圆："+inTime);
						rpb_timeProgress.setInProgress(inTime);
					}
				}

				// 循环
				if (!isOver) {
					Message msg2 = handler.obtainMessage();
					msg2.what = IN_MSG;
					handler.sendMessageDelayed(msg2, 100);
				}

			}
		}
	};

	// 给单词赋值 flag 0初始状态没有动画 1认识 2不认识
	private void initWord(int flag) {
		if (list != null && list.size() > 0 && currentPosition <= list.size()) {
			if (flag == FLAG_KNOW) {
				// 认识动画
				ScaleAnimation sAnimation = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.5f, Animation.RELATIVE_TO_SELF,
						0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

				sAnimation.setDuration(250);
				sAnimation.setFillAfter(true);

				sAnimation.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						ScaleAnimation sAnimation = new ScaleAnimation(1.5f, 1.0f, 1.5f, 1.0f,
								Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
						sAnimation.setDuration(250);
						sAnimation.setFillAfter(true);
						iv_know.startAnimation(sAnimation);
					}
				});

				iv_know.startAnimation(sAnimation);
			} else if (flag == FLAG_UNKNOW) {
				// 不认识动画
				ScaleAnimation sAnimation = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.5f, Animation.RELATIVE_TO_SELF,
						0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

				sAnimation.setDuration(250);
				sAnimation.setFillAfter(true);

				sAnimation.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						ScaleAnimation sAnimation = new ScaleAnimation(1.5f, 1.0f, 1.5f, 1.0f,
								Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
						sAnimation.setDuration(250);
						sAnimation.setFillAfter(true);
						iv_unknow.startAnimation(sAnimation);
					}
				});

				iv_unknow.startAnimation(sAnimation);
			}

			if (currentPosition <= list.size() - 1) {
				CadicatesBean cadicatesBean = list.get(currentPosition);
				Eword eword = wordDao.findByWordId(cadicatesBean.getWid());
				List<EwordMeaning> wordmMeanings = wordMeaningDao.findByWordId(cadicatesBean.getWid());

				if (eword != null && !TextUtils.isEmpty(eword.word)) {
					cadicatesBean.setWord(eword.word);
					cadicatesBean.setPhonetic(eword.en_phonetic);
					cadicatesBean.setMeans(ListUtils.transferMeanList(wordmMeanings));
					tv_word.setText(Html.fromHtml(eword.word));
					if (!TextUtils.isEmpty(eword.en_phonetic) && !"[]".equals(eword.en_phonetic)) {
						ll_phonetic.setVisibility(View.VISIBLE);
						tv_phonetic.setText(Html.fromHtml(eword.en_phonetic));
					} else {
						ll_phonetic.setVisibility(View.INVISIBLE);
					}
				} else {
					// 筛到 单词不存在的，就跳过去
					notExist();
				}
			}

			tv_knownNum.setText(getResources().getString(R.string.word_known) + "  " + knownList.size());
			tv_unknownNum.setText(getResources().getString(R.string.word_unknown) + "  " + unknownList.size());
		}
	}

	private void showHintDialog() {
		// 暂停当前计时
		isPause = true;
		// 有复习计划未完成
		View view = LayoutInflater.from(mContext).inflate(R.layout.layout_rob_warn_dialog, null);

		final Dialog dialog = new Dialog(mContext, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_content.setText(R.string.word_filter_exit_msg);
		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		ll_layout1.setVisibility(View.VISIBLE);
		ll_layout2.setVisibility(View.GONE);

		Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
		Button btn_no = (Button) view.findViewById(R.id.btn_no);
		btn_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
					isPause = false;
				}
			}
		});
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing() && handler != null) {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "word_filter_backBtn");

					SpeechTTSUtil.getInstance(mContext).close();
					dialog.cancel();
					handler.removeMessages(IN_MSG);
					finish();
				}

			}
		});
		dialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				isPause = false;
			}
		});

	}

	/**
	 * 所有已筛完，没有不认识的， 就弹出一个对话框
	 */
	private void showWordFinishDialog() {
		// 有复习计划未完成
		View view = LayoutInflater.from(mContext).inflate(R.layout.layout_rob_warn_dialog, null);

		final Dialog dialog = new Dialog(mContext, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_content.setText(R.string.word_filter_finish);
		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		ll_layout1.setVisibility(View.GONE);
		ll_layout2.setVisibility(View.VISIBLE);

		Button btn_know = (Button) view.findViewById(R.id.btn_know);
		btn_know.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
					submitGroup();
				}
			}
		});

	}

	private void submitGroup() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}

		mWordTask.submitGroup("2", "[" + ListUtils.getWidStrByDouhao(knownList, list) + "]",
				"[" + ListUtils.getWidStrByDouhao(unknownList, list) + "]", DateUtil.getLocalTimeZone(),
				new HttpRequestAbstractCallBack(mContext,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();
						try {
							BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
							if (baseBean != null && 200 == baseBean.getStatus_code()) {
								// 提交成功
								WordHomeDataUtil.putTodayStudying(mContext, 1);
								if (unknownList != null) {
									WordHomeDataUtil.putWordStudyingNum(mContext, unknownList.size());
								}
								if (knownList != null) {
									WordHomeDataUtil.putWordMasterNum(mContext, knownList.size());
								}

								finish();

							} else {
								AppUtil.showToast(mContext, R.string.load_net_data_failure);
							}
						} catch (Exception e) {
							LogUtils.d("json数据异常");
							LogUtils.exception(e);
						}
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						LogUtils.e(msg);
						AppUtil.dismissProgressDialog();
						AppUtil.showToast(mContext, R.string.load_net_data_failure);
					}
				});

	}

	private void known(boolean isClick) {
		knownList.add(currentPosition);
		currentPosition++;
		if (currentPosition == list.size()) {
			// 让最后一个 也有动画，但是word不能变化
			initWord(FLAG_KNOW);
		}
		if (currentPosition <= list.size()) {
			if (currentPosition <= list.size() - 1) {
				initWord(FLAG_KNOW);
				if (isClick) {
					// 让当前内循环结束，重新计时
					handler.removeMessages(IN_MSG);
					rpb_timeProgress.setInProgress(0);
					inTime = 0;
					Message inMessage = handler.obtainMessage();
					inMessage.what = IN_MSG;
					handler.sendMessageDelayed(inMessage, 100);
				}
				// 如果剩下的单词 不足10个了，去请求下一组的单词。、
				if (currentPosition == list.size() - 1 - 10) {
					getNextFilterWord();
				}
			} else {
				// 这一组的筛完了 没有下一组了
				LogUtils.d("所有的都已经筛选完了");
				if (isLoading) {
					AppUtil.showProgressDialog(mContext);
				} else {
					intentWordGroupBuild(true);
				}
			}
		}
	}

	/**
	 * 不存在的
	 */
	private void notExist() {
		currentPosition++;
		if (currentPosition == list.size()) {
			// 让最后一个 也有动画，但是word不能变化
			initWord(FLAG_NOT_EXIST);
		}
		if (currentPosition <= list.size()) {
			if (currentPosition <= list.size() - 1) {
				initWord(FLAG_NOT_EXIST);
				// 如果剩下的单词 不足10个了，去请求下一组的单词。、
				if (currentPosition == list.size() - 1 - 10) {
					getNextFilterWord();
				}
			} else {
				// 这一组的筛完了 没有下一组了
				LogUtils.d("所有的都已经筛选完了");
				if (isLoading) {
					AppUtil.showProgressDialog(mContext);
				} else {
					intentWordGroupBuild(true);
				}
			}
		}
	}

	private boolean unknown(boolean isClick) {
		boolean isOver = false;
		unknownList.add(currentPosition);
		currentPosition++;
		if (currentPosition == list.size()) {
			// 让最后一个 也有动画，但是word不能变化
			initWord(FLAG_UNKNOW);
		}
		if (currentPosition <= list.size()) {
			if (currentPosition <= list.size() - 1) {
				initWord(FLAG_UNKNOW);
				if (isClick) {
					// 让当前内循环结束，重新计时
					handler.removeMessages(IN_MSG);
					rpb_timeProgress.setInProgress(0);
					inTime = 0;
					Message inMessage = handler.obtainMessage();
					inMessage.what = IN_MSG;
					handler.sendMessageDelayed(inMessage, 100);
				}
				// 判断用户筛选的不认识单词是否到 20个了
				if (unknownList.size() >= 20) {
					LogUtils.d("不认识的已经到了20个");
					handler.removeMessages(IN_MSG);
					isOver = true;
					intentWordGroupBuild(false);
					return isOver;
				}

				// 如果剩下的单词 不足10个了，去请求下一组的单词。、
				if (currentPosition == list.size() - 1 - 10) {
					getNextFilterWord();
				}

			} else {
				// 这一组的筛完了 没有下一组了
				LogUtils.d("所有的都已经筛选完了");
				if (isLoading) {
					AppUtil.showProgressDialog(mContext);
					isOver = false;
				} else {
					intentWordGroupBuild(true);
					isOver = true;
				}

				return isOver;
			}
		}
		return isOver;
	}

	/**
	 *
	 * @param isAllWordFilter是不是所有的单词都筛选完了
	 */
	private void intentWordGroupBuild(boolean isAllWordFilter) {
		if (handler != null && unknownList != null) {
			// 判断不认识的单词 等于20个，或者 单词已经筛完了，会跳转。
			if (isError) {
				AppUtil.showToast(this, R.string.word_filter_error);
				return;
			}
			handler.removeMessages(IN_MSG);
			YsApplication myApplication = (YsApplication) this.getApplication();
			myApplication.setList(list);
			myApplication.setKnownList(knownList);
			myApplication.setUnknownList(unknownList);
			if (isAllWordFilter) {
				if (unknownList == null || unknownList.size() == 0) {
					// 筛完了，也没有不认识的词
					showWordFinishDialog();
					return;
				}
			}

			startActivity(new Intent(this, WordGroupBuildActivity.class));
			SpeechTTSUtil.getInstance(this).close();
			this.finish();

		}
	}

	@Override
	public void onBackPressed() {
		showHintDialog();
	}

	/**
	 * 获取下一组 筛选单词
	 */
	private void getNextFilterWord() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			// 就让筛选过程停止
			AppUtil.showToast(this, R.string.no_network);
			isPause = true;
			isError = true;
			handler.removeMessages(IN_MSG);
			return;
		}

		isLoading = true;

		mWordTask.getNextFilterWord("simple", "[" + ListUtils.getWidStrByDouhao(list) + "]",
				new HttpRequestAbstractCallBack(mContext,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();
						try {
							FilterWordResponse filterWordResponse = JSON.parseObject(result, FilterWordResponse.class);
							if (filterWordResponse != null) {
								int status_code = filterWordResponse.getStatus_code();
								if (200 == status_code) {
									String data = filterWordResponse.getData();
									if (!TextUtils.isEmpty(data)) {
										FilterWordData filterWordData = JSON.parseObject(data, FilterWordData.class);
										if (filterWordData != null) {
											List<CadicatesBean> cadicates = filterWordData.getCandidates();
											list.addAll(cadicates);
										}
									}
								} else if (status_code >= 400) {
									// 就让筛选过程停止
									AppUtil.showToast(mContext, R.string.word_filter_error);
									isPause = true;
									isError = true;
									handler.removeMessages(IN_MSG);
								}

							}
						} catch (Exception e) {
							LogUtils.d("json数据异常");
							LogUtils.exception(e);
						}
						isLoading = false;
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						LogUtils.e(msg);
						AppUtil.dismissProgressDialog();
						// 就让筛选过程停止
						AppUtil.showToast(mContext, R.string.word_filter_error);
						isPause = true;
						isError = true;
						handler.removeMessages(IN_MSG);
						isLoading = false;
					}
				});

	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			showHintDialog();
			break;
		case R.id.btn_known:
			if (AppUtil.isFastClick()) {
				return;
			}
			known(true);
			break;
		case R.id.btn_unknown:
			if (AppUtil.isFastClick()) {
				return;
			}
			unknown(true);
			break;
		case R.id.iv_speak:
			String string = tv_word.getText().toString();
			if (!TextUtils.isEmpty(string)) {
				SpeechTTSUtil.getInstance(this).speak(string);
			}
			break;
		default:
			break;
		}
	}
}
